package com.dream.inspect.modules.app.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.dream.inspect.common.utils.DateUtils;
import com.dream.inspect.modules.job.common.ScheduleCommonMethod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.toolkit.StringUtils;
import com.dream.inspect.common.exception.RRException;
import com.dream.inspect.common.utils.R;
import com.dream.inspect.modules.app.constants.AttrConstants;
import com.dream.inspect.modules.app.controller.common.CommonMethod;
import com.dream.inspect.modules.business.dao.SuperviseProjectDao;
import com.dream.inspect.modules.business.dao.SuperviseStandardDao;
import com.dream.inspect.modules.business.dao.SuperviseTempletConfDao;
import com.dream.inspect.modules.business.entity.SuperviseProjectEntity;
import com.dream.inspect.modules.business.entity.SuperviseProjectRecordEntity;
import com.dream.inspect.modules.business.entity.SuperviseQuestionEntity;
import com.dream.inspect.modules.business.entity.SuperviseStandardEntity;
import com.dream.inspect.modules.business.entity.SuperviseTargetEntity;
import com.dream.inspect.modules.business.entity.SuperviseTempletEntity;
import com.dream.inspect.modules.business.service.SuperviseImageService;
import com.dream.inspect.modules.business.service.SuperviseProjectRecordService;
import com.dream.inspect.modules.business.service.SuperviseProjectService;
import com.dream.inspect.modules.business.service.SuperviseQuestionModifyService;
import com.dream.inspect.modules.business.service.SuperviseQuestionService;
import com.dream.inspect.modules.business.service.SuperviseRecordService;
import com.dream.inspect.modules.business.service.SuperviseStandardService;
import com.dream.inspect.modules.business.service.SuperviseTargetService;
import com.dream.inspect.modules.business.service.SuperviseTempletService;
import com.dream.inspect.modules.business.service.SysMessageService;
import com.dream.inspect.modules.sys.dao.SysDeptDao;
import com.dream.inspect.modules.sys.entity.SysUserEntity;
import com.dream.inspect.modules.sys.service.SysUserService;

/**
 * 专项督察
 */


@Controller
@RequestMapping("/app/project")
public class AppSuperviseProjectController {

    @Autowired
    SuperviseStandardService superviseStandardService;
    @Autowired
    SuperviseProjectService superviseProjectService;
    @Autowired
    SuperviseTargetService superviseTargetService;
    @Autowired
    SuperviseProjectRecordService superviseProjectRecordService;
    @Autowired
    SuperviseRecordService superviseRecordService;
    @Autowired
    SuperviseTempletService superviseTempletService;
    @Autowired
    SuperviseQuestionService superviseQuestionService;
    @Autowired
    SuperviseQuestionModifyService superviseQuestionModifyService;
    @Autowired
    ScheduleCommonMethod scheduleCommonMethod;
    @Autowired
    SysUserService sysUserService;
    @Autowired
    SysDeptDao sysDeptDao;

    @Autowired
    SuperviseTempletConfDao superviseTempletConfDao;
    @Autowired
    SuperviseStandardDao superviseStandardDao;
    @Autowired
    SysMessageService sysMessageService;
    @Autowired
    CommonMethod commonMethod;
    @Autowired
    SuperviseProjectDao superviseProjectDao;


    /**
     * 标准类型列表
     * 
     * @param params
     * @return
     */
    @ResponseBody
    @RequestMapping("/findStandardType")
    public R findStandardType(Map<String, Object> params){
        List<SuperviseStandardEntity> dataList = new ArrayList<SuperviseStandardEntity>();
        dataList = superviseStandardService.findStandardType(params);
        return R.ok().put(AttrConstants.DATA, dataList);
    }
    
    
    /**
     * 查询全部专项列表
     * 
     * @param params
     * @return
     */
    @ResponseBody
    @RequestMapping("/allSuperviseProjectList")
    public R findAllList(@RequestParam Map<String, String> params){
        int countNum = 0;
        List<SuperviseProjectEntity> dataList = new ArrayList<SuperviseProjectEntity>();
        countNum = superviseProjectService.findAllListCount(params);
        if (countNum != 0) {
            dataList = superviseProjectService.findAllList(params);
        }
        return R.ok().put(AttrConstants.DATA, dataList).put(AttrConstants.COUNT_NUM, countNum);
    }
    
    /**
     * 查询联合督察和自察专项列表
     * 
     * @param params
     * @return
     */
    @ResponseBody
    @RequestMapping("/findZczxAndLhdc")
    public R findZczxAndLhdc(@RequestParam Map<String, String> params){
        int countNum = 0;
        List<SuperviseProjectEntity> dataList = new ArrayList<SuperviseProjectEntity>();
        countNum = superviseProjectService.findZczxAndLhdcCount(params);
        if (countNum != 0) {
            dataList = superviseProjectService.findZczxAndLhdcList(params);
        }
        return R.ok().put(AttrConstants.DATA, dataList).put(AttrConstants.COUNT_NUM, countNum);
    }
    
    /**
     * 查询专项详情
     * 
     * @param params
     * @return
     */
    @ResponseBody
    @RequestMapping("/findDetailInfo")
    public R findDetailInfo(@RequestParam Map<String, String> params){
        
        SuperviseProjectEntity dataDetail = new SuperviseProjectEntity();
        dataDetail = superviseProjectService.findDetailInfo(params);
        return R.ok().put(AttrConstants.DATA, dataDetail);
    }
    
    /**
     * 查询专项详情的项目进程
     * 
     * @param params 专项的ID
     * @return
     */
    @ResponseBody
    @RequestMapping("/findSuperviseProjectRecordList")
    public R findSuperviseProjectRecordList(@RequestParam Map<String, String> params){
        int countNum = 0;
        countNum = superviseProjectRecordService.findSuperviseProjectRecordListCount(params);
        List<SuperviseProjectRecordEntity> sprList = new ArrayList<SuperviseProjectRecordEntity>();
        if (countNum != 0) {
            sprList = superviseProjectRecordService.findSuperviseProjectRecordList(params);
        }
        return R.ok().put(AttrConstants.DATA, sprList).put(AttrConstants.COUNT_NUM, countNum);
    }
    
    /**
     * 查询专项详情的实施单位
     * 
     * @param params 专项的ID
     * @return
     */
    @ResponseBody
    @RequestMapping("/findSuperviseTargetList")
    public R findSuperviseTargetList(@RequestParam Map<String, String> params){
        int countNum = 0;
        countNum = superviseTargetService.findSuperviseTargetListCount(params);
        List<SuperviseTargetEntity> targetList = new ArrayList<SuperviseTargetEntity>();
        if (countNum != 0) {
            targetList = superviseTargetService.findSuperviseTargetList(params);
        }
        
        return R.ok().put(AttrConstants.DATA, targetList).put(AttrConstants.COUNT_NUM, countNum);
    }
    
    /**
     * 督察模板
     * 
     * @param params 模板ID
     * @return
     */
    @ResponseBody
    @RequestMapping("/findSuperviseQuestionListCountNoImage")
    public R findSuperviseQuestionListCountNoImage(@RequestParam Map<String, String> params){

        int countNum = 0;
        countNum = superviseQuestionService.findSuperviseQuestionListNoImageCount(params);
        List<SuperviseQuestionEntity> srsList = new ArrayList<SuperviseQuestionEntity>();
        if (countNum != 0) {
            srsList = superviseQuestionService.findSuperviseQuestionListNoImage(params);
        }
        
        return R.ok().put(AttrConstants.DATA, srsList).put(AttrConstants.COUNT_NUM, countNum);
    }

    /**
     * 督察立项insert
     * 
     * @param params (督察立项相关信息)
     * @return
     */
    @ResponseBody
    @RequestMapping("/insertSuperviseProject")
    @Transactional(rollbackFor = Exception.class)
    public R insertSuperviseProject(@RequestParam Map<String, String> params){
    	
        try {
        	String id = params.get("id");
        	if (StringUtils.isEmpty(id)) {
        		// 督察立项表
                Long spId = superviseProjectService.insertSuperviseProject(params);
                if (spId == 0L) {
                	return R.error("申请立项失败！");
                } else {
                	//督察专项进程记录表
                	superviseProjectRecordService.insertSuperviseProjectRecordService(params, spId);
                	//督察对象表
                	insertSuperviseTarget(params, spId);
                    scheduleCommonMethod.addTimeMessage(DateUtils.stringToDate(params.get("jzrq"), DateUtils.DATE_TIME_PATTERN),"2",spId+"");
                }
        	} else {
        		 // 督察立项表
                boolean blnFlag = superviseProjectService.updateSuperviseProject(params);
                
                if (!blnFlag) {
                	return R.error("处理失败！");
                }
                //督察专项进程记录表
            	superviseProjectRecordService.insertSuperviseProjectRecordService(params, Long.valueOf(id));
                //删除督察对象的数据
                superviseTargetService.deleteSuperviseTargetByCondition(params);
                //督察对象表
            	insertSuperviseTarget(params, Long.valueOf(id));
                scheduleCommonMethod.addTimeMessage(DateUtils.stringToDate(params.get("jzrq"), DateUtils.DATE_TIME_PATTERN),"2",id);

        	}
        	
        	//insert sys_message
        	String noticeTitle = "您有新的立项待审批";
        	params.put("noticeTitle", noticeTitle);
        	String contentText = "您有新的立项" + params.get("titleName") + "待审批";
        	params.put("noticeContent", contentText);
        	String deptId = params.get("zbdwId");
        	String roles = "";
        	if (StringUtils.isNotEmpty(deptId)) {
        		roles = commonMethod.getRolesAByDeptId(deptId); //接收角色
        	}
        	if (StringUtils.isNotEmpty(roles)) {
        		params.put("roles", roles);
        	}
            params.put("deptId", deptId);
            sysMessageService.insertMessage(params);
            
        } catch (RRException rre) {
            System.out.println(rre.getMessage());
            return R.error(rre.getMessage());
        } catch (Exception e) {
            return R.error("申请立项失败！");
        }
        
        return R.ok();
    }
    
    /**
     * 督察立项update(取消立项，驳回立项，审批立项)
     * 
     * @param params (督察立项相关信息)
     * @return
     */
    @ResponseBody
    @RequestMapping("/updateSuperviseProject")
    @Transactional(rollbackFor = Exception.class)
    public R updateSuperviseProject(@RequestParam Map<String, String> params){
        try {
        	Long spId = Long.valueOf(params.get("id"));
            String lxspzt  = params.get("lxspzt");//立项审批状态(0：待审核，1：审核未通过(驳回)，2：审核通过)
            String czzt = params.get("czzt");//操作状态(1：申请立项，2：取消立项，3：通过立项，4：驳回立项，5：执行立项，6：申请办结，7：取消办结，8：通过办结，9：驳回办结)
            String noticeTitle = "";
            String contentText = "";
            String titleName = "";
            Long sprId = 0L;
            String userName = "";
            String sqCzzt = "";
            SuperviseProjectEntity spEntity = superviseProjectService.findSuperviseProjectForCzztById(params);
            if (spEntity != null) {
            	titleName = spEntity.getTitleName();
            	sprId = spEntity.getLxspr();
            	sqCzzt = spEntity.getCzzt();
            }
            boolean blnFlg = false;
            //取消立项 操作 后台需判断该立项是否已被驳回或取消或通过
            //通过立项 操作 后台需判断该立项是否已被驳回或取消或通过
            if ("2".equals(czzt) || "3".equals(czzt)) {
            	if("2".equals(sqCzzt) || "3".equals(sqCzzt) || "4".equals(sqCzzt)) {
            		blnFlg = true;
            	}
            }
            //申请办结 操作后台需判断该立项是否已申请办结
            if ("6".equals(czzt)) {
            	if("6".equals(sqCzzt) || "8".equals(sqCzzt)) {
            		blnFlg = true;
            	}
            }
            //取消办结操作 后台需判断该立项是否已取消办结或已驳回办结或已通过办结
            //通过办结操作 后台需判断该立项是否已取消办结或已驳回办结或已通过办结；
            //驳回办结操作 后台需判断该立项是否已取消办结或已驳回办结或已通过办结；
            if ("7".equals(czzt) || "8".equals(czzt) || "9".equals(czzt)) {
            	if("7".equals(sqCzzt) || "8".equals(sqCzzt) || "9".equals(sqCzzt)) {
            		blnFlg = true;
            	}
            }
            
            if (blnFlg) {
            	String msg = commonMethod.getMsgInfo(sqCzzt);
            	msg = "其他用户已" + msg + "!";
            	return R.error("2",msg);
            }
            
            // 更新督察立项表状态
            boolean blnFlag = superviseProjectService.updateSuperviseProject(params);
            if (!blnFlag) {
            	return R.error("处理失败！");
            } else {
	            //插入督察专项进程记录表
	        	superviseProjectRecordService.insertSuperviseProjectRecordService(params, spId);
                if ("3".equals(czzt)) {
                    scheduleCommonMethod.addTimeMessage(spEntity.getJzrq(),"3",spId+"");
                }
            }
            String deptId = params.get("userDeptId");
           	//insert sys_message
            if (StringUtils.isNotEmpty(lxspzt)) {
            	SysUserEntity suEntity = sysUserService.selectById(sprId);
            	if (suEntity != null) {
            		userName = suEntity.getName();
            	}
            	if ("1".equals(lxspzt)) {
            		noticeTitle = "您的立项已驳回";
            		contentText = "您的立项" + titleName + "已驳回";
            	} else if ("2".equals(lxspzt) && "3".equals(czzt)) {
            		noticeTitle = "您的立项已通过";
            		contentText = "您的立项" + titleName + "已通过";
            		//实施单位A/B角色的消息
            		insertDcssdwMessage(spEntity, params, lxspzt);
            	} else if ("3".equals(lxspzt)) {
            		noticeTitle = "您有新的专项办结";
            		contentText = "您有新的专项办结" + titleName + "待审批";
            	} else if ("4".equals(lxspzt)) {
            		noticeTitle = "您的专项办结已驳回";
            		contentText = "您的专项办结" + titleName + "已驳回";
            	} else if ("5".equals(lxspzt)) {
            		noticeTitle = "您的专项办结已通过";
            		contentText = "您的专项办结" + titleName + "已通过";
            		//通知实施单位A/B角色的消息
//            		insertDcssdwMessage(spEntity, params, lxspzt);
            		

            	}
            	
            	if (StringUtils.isNotEmpty(noticeTitle)) {
                	params.put("noticeTitle", noticeTitle);
                }
                if (StringUtils.isNotEmpty(contentText)) {
                	params.put("noticeContent", contentText);
                }
            	
                params.put("deptId", deptId);
            	String roles = "";
            	if (StringUtils.isNotEmpty(deptId)) {
            		if ("3".equals(lxspzt)) {
            			roles = commonMethod.getRolesAByDeptId(deptId); //接收角色
            		} else {
            			roles = commonMethod.getRolesBByDeptId(deptId); //接收角色
            		}
            	}
            	if (StringUtils.isNotEmpty(roles)) {
            		params.put("roles", roles);
            	}
            	sysMessageService.insertMessage(params);
            }
            
        } catch (RRException rre) {
            System.out.println(rre.getMessage());
            return R.error(rre.getMessage());
        } catch (Exception e) {
            return R.error("处理失败！");
        }
        
        return R.ok();
    }
    
    /**
     * 查询立项信息
     * 
     * @param params
     * @return
     */
    @ResponseBody
    @RequestMapping("/findSuperviseProjectById")
    public R findSuperviseProjectById(@RequestParam Map<String, String> params){
    	
    	SuperviseProjectEntity spEntity = new SuperviseProjectEntity();
    	spEntity = superviseProjectService.findSuperviseProjectById(params);

        return R.ok().put(AttrConstants.DATA, spEntity);
    }


    /**
     * 查询所有模板根据用户
     */
    @ResponseBody
    @RequestMapping("/findAllModel")
    public R findAllModel(@RequestParam Map<String, Object> params) {
        params.put("flag","3");
        List<SuperviseTempletEntity> list = superviseTempletService.findAllModelToUserIdList(params);
        return R.ok().put("data", list);
    }
    
    private void insertSuperviseTarget(Map<String, String> params, Long spId) {
    	
    	String dcssfwList = params.get("dcssfwList");
    	if(StringUtils.isNotEmpty(dcssfwList)) {
		
    		List<SuperviseTargetEntity> stList = JSON.parseArray(dcssfwList, SuperviseTargetEntity.class);
    		String userId = params.get("userId");
    		if (stList != null && stList.size() > 0) {
    			for (SuperviseTargetEntity temp : stList) {
    				temp.setProjectId(spId);
    				temp.setCreateUser(Long.valueOf(userId));           //创建人id
    		        temp.setUpdateUser(Long.valueOf(userId));           //更新人id
    		        temp.setSsStatus("0");
                	//督察对象表
                	superviseTargetService.insertSuperviseTarget(temp);
    			}
    		}
    	}
    	
    }
    
    /**
     * 
     * @param spEntity
     * @param params
     * @param lxspzt 专项审批状态
     */
	private void insertDcssdwMessage(SuperviseProjectEntity spEntity, Map<String, String> params, String lxspzt) {
	    	
    	String dcssfwList = spEntity.getProjectJsonInfo();
    	if(StringUtils.isNotEmpty(dcssfwList)) {
		
    		List<SuperviseTargetEntity> stList = JSON.parseArray(dcssfwList, SuperviseTargetEntity.class);
    		if (stList != null && stList.size() > 0) {
    			String titleName = "";
    			String noticeTitle = "";
                String contentText = "";
                String roles = "";
    			for (SuperviseTargetEntity temp : stList) {

    				if (spEntity != null) {
    	            	titleName = spEntity.getTitleName();
    	            }
    				if ("2".equals(lxspzt)) {
    					noticeTitle = "您有新的专项待执行";
    					contentText = "您有新的专项" + titleName + "待执行！";
    				} else if ("3".equals(lxspzt)) {
    					noticeTitle = "专项办结";
    					contentText = "专项" + titleName + "已办结，请注意！";
    				}else if ("5".equals(lxspzt)) {
                        noticeTitle = "您的专项办结已通过";
                        contentText = "您的专项办结已通过" + titleName + "已办结，请注意！";
                    }
    	            if (StringUtils.isNotEmpty(noticeTitle)) {
    	            	params.put("noticeTitle", noticeTitle);
    	            }
    	            if (StringUtils.isNotEmpty(contentText)) {
    	            	params.put("noticeContent", contentText);
    	            }
    	        	String deptId = String.valueOf(temp.getToSsdwId());
                    params.put("deptId", deptId);
    	        	if (StringUtils.isNotEmpty(deptId)) {
    	        		roles = commonMethod.getRolesByDeptId(deptId); //接收角色
    	        	}
    	        	if (StringUtils.isNotEmpty(roles)) {
    	        		params.put("roles", roles);
    	        	}
    	        	sysMessageService.insertMessage(params);
    				
    			}
    		}
    	}
    	
    }

    /**
     * 查询专项是否办结
     */
    @RequestMapping("/findProjectStatus")
    @ResponseBody
    public R findProjectStatus(String projectId){
        String status = superviseProjectDao.selectAllById(projectId).getProjectStatus();
        if(StringUtils.isEmpty(status)){
            return R.error();
        }
        return R.ok().put("data",status);
    }


}
